package com.ciwong.epaper.ui;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.NewRegistUser;
import com.ciwong.epaper.modules.login.LoginContract;
import com.ciwong.epaper.modules.login.LoginPresenterImpl;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;

import java.util.regex.Pattern;

/**
 * 注册账号界面
 *
 * @author bin
 * @version ciwong v.1.0 2015/9/29 9:31
 * @since ciwong v.1.0
 */
public class RegisterActivity extends BaseActivity implements LoginContract.LoginView {
    private EditText etName, etPass, etPass1;

    private CheckBox cb;

    private Button btnReg;

    private TextView tvRule;
    private String phoneNumber, verity_code;
    private LoginContract.LoginPresenter mLoginPresenter;
    private TextView err_tips_tv;
    private final int TIPS_GONE = 1;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIPS_GONE:
                    //错误提示
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    break;
            }
        }
    };
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            btnReg.setEnabled(cb.isChecked() && etName.length() > 0
                    && etPass.length() > 0 && etPass1.length() > 0);
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_register;
    }

    @Override
    protected void findViews() {
        etName = (EditText) findViewById(R.id.reg_name);
        etPass = (EditText) findViewById(R.id.reg_pass);
        etPass1 = (EditText) findViewById(R.id.reg_pass1);
        cb = (CheckBox) findViewById(R.id.cb_is_agree);
        tvRule = (TextView) findViewById(R.id.tv_ciwong_rule);
        btnReg = (Button) findViewById(R.id.btn_reg);
        err_tips_tv = (TextView) findViewById(R.id.err_tips_tv);
    }

    @Override
    protected void initEvent() {
        cb.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        watcher.afterTextChanged(null);
                    }
                });
        tvRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseJumpManager.jumpToBrowser(RegisterActivity.this,
                        R.string.go_back, EConstants.RULE, null);
            }
        });

        etName.addTextChangedListener(watcher);
        etPass.addTextChangedListener(watcher);
        etPass1.addTextChangedListener(watcher);

        btnReg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(phoneNumber) && !TextUtils.isEmpty(verity_code)) {
                    register(phoneNumber, verity_code);
                }

            }
        });
    }

    private void register(String phoneNumber, String verity_code) {
        String userName = etName.getText().toString().trim();
        final String pass = etPass.getText().toString().trim();
        final String pass2 = etPass1.getText().toString().trim();
        if (!MeUtil.validateUserName(userName)) {
            errTips(err_tips_tv, getString(R.string.register_name_hint_fail));
            //showToastError(R.string.register_name_hint_fail);
        } else if (!MeUtil.validatePassword2(pass)) {
            errTips(err_tips_tv, getString(R.string.register_password_hint_fail));
            //showToastError(R.string.register_password_hint_fail);
        } else if (!pass.equals(etPass1.getText().toString())) {
            errTips(err_tips_tv, getString(R.string.pass_not_same));
            // showToastError(R.string.pass_not_same);
        } else if (!NetworkUtils.isOnline()) {
            errTips(err_tips_tv, getString(R.string.request_failed));
        } else {
            showMiddleProgressBar(getTitleText());
            btnReg.setEnabled(false);
            MeDao.getInstance().registerUser(EApplication.BRAND_ID + "", phoneNumber, verity_code, userName, "1", pass, pass2,
                    new BaseExtCallBack(RegisterActivity.this) {
                        @Override
                        public void success(Object data) {
                            if (data != null) {
                                //非游客登陆模式
                                EConstants.IS_YOUKE = false;
                                //不再返回登陆页面直接走登陆逻辑
                                NewRegistUser user = (NewRegistUser) data;
                                mLoginPresenter.validateCredentials(user.getMobile(), pass, "", "");
                                if (user != null)
                                    MeDao.getInstance().getUserPoint(user.getUser_id() + "");
//                                loginByPhone(user.getMobile(),pass);
                                // MeJumpManager.jumpToLogin2(RegisterActivity.this,0,user.getMobile(),pass,EConstants.LoginFrom.LOGIN_FROM_REGIST);
                                /*Intent intent = new Intent();
                                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ,
                                        user);
                                intent.putExtra(BaseIntentFlag.INTENT_FLAG_STR,
                                        pass);
                                setResult(RESULT_OK, intent);*/
                                // finish();
                            } else {
                                errTips(err_tips_tv, "注册失败");
                                //showToastError("注册失败");
                            }
                            watcher.afterTextChanged(null);
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            watcher.afterTextChanged(null);
                            if (errorCode != 10004 && errorCode != 27 && errorCode != 17) {
                                errTips(err_tips_tv, String.valueOf(data));
                            }
                            //showToastError(String.valueOf(data));
                            hideMiddleProgressBar();
                        }

                        @Override
                        public void failed(Object data) {
                            watcher.afterTextChanged(null);
                            DialogUtil.showFailedToastByErrorType(RegisterActivity.this, data);

//                            if (data instanceof NoConnectionError)
//                            {
//                                errTips(err_tips_tv,getString(R.string.connect_disable));
//
//                            }
//                            else if (data instanceof TimeoutError)
//                            {
//                                errTips(err_tips_tv,getString(R.string.connect_timeout));
//
//                            }
//                            else
//                            {
//                                errTips(err_tips_tv,getString(R.string.unknown_error));
//                            }
                            //showToastError(R.string.connect_disable);
                            hideMiddleProgressBar();
                        }
                    });
        }
    }
//    /**
//     * 登录失败(其他错误)
//     *
//     * @param data
//     *            失败信息
//     */
//    private void loginFailed(Object data)
//    {
//        DialogUtil.showFailedToastByErrorType(RegisterActivity.this,data);
//    }
//
//    /**
//     * 登录失败(业务错误)
//     *
//     * @param errorCode
//     *            错误码
//     * @param msg
//     *            错误信息
//     */
//    private void loginFailed(int errorCode, String msg)
//    {
//        switch (errorCode)
//        {
//            case EConstants.LOGIN_ERROR_CODE_ACCOUNT_ERROR:
//                showToastError(R.string.login_error_account);
//                break;
//            case EConstants.LOGIN_ERROR_CODE_PWD_ERROR_SPECIAL:
//            case EConstants.LOGIN_ERROR_CODE_PWD_ERROR:
//                showToastError(R.string.login_error_password);
//                break;
//            default:
//                showToastError(errorCode + String.valueOf(msg));
//                break;
//        }
//    }


//    //手机号登录逻辑
//
//    /**
//     * 手机号登陆
//     */
//    private void loginByPhone(final String account,final String password){
//        //品牌ＩＤ先写死　　为１
//        MeDao.getInstance().getUserIdByPhone(EApplication.BRAND_ID, account, new BaseCallBack() {
//            @Override
//            public void failed(int errorCode, Object data) {
//
//                loginFailed(errorCode, String.valueOf(data));
//                MeJumpManager.jumpToLogin2(RegisterActivity.this,0,account,password,EConstants.LoginFrom.LOGIN_FROM_REGIST);
//            }
//
//            @Override
//            public void failed(Object data) {
//                loginFailed(data);
//                MeJumpManager.jumpToLogin2(RegisterActivity.this,0,account,password,EConstants.LoginFrom.LOGIN_FROM_REGIST);
//
//            }
//
//            @Override
//            public void success(Object data) {
//                NewUserInfo newUserInfo=(NewUserInfo)data;
//                Boolean isPhoneLogin;
//                //根据USERId去登陆
//                String user_Id=newUserInfo.getUser_id();
//                isPhoneLogin=true;
//                if(!TextUtils.isEmpty(user_Id)){
//                    loginByUserID(account,user_Id,password,isPhoneLogin);
//                }
//
//            }
//        });
//    }

//    /**
//     * USERIDD登陆
//     * @param account
//     * @param password
//     */
//    private  void loginByUserID(final String phoneNumber,final String account,final String password,final Boolean boolea){
//        MeDao.getInstance().getUserToken(((EApplication) getApplication()), account, password,
//                 new BaseCallBack()
//                {
//                    @Override
//                    public void failed(int errorCode, Object data)
//                    {
//                        loginFailed(errorCode, String.valueOf(data));
//                        MeJumpManager.jumpToLogin2(RegisterActivity.this,0,phoneNumber,password,EConstants.LoginFrom.LOGIN_FROM_REGIST);
//                    }
//
//                    @Override
//                    public void failed(Object data)
//                    {
//                        loginFailed(data);
//                        MeJumpManager.jumpToLogin2(RegisterActivity.this,0,account,password,EConstants.LoginFrom.LOGIN_FROM_REGIST);
//
//                    }
//
//                    @Override
//                    public void success(Object data) {
//                        // loginSuccess();
//                        // 新版书柜登录
//                        EJumpManager.jumpToMain(0, RegisterActivity.this);
//                        finish();
//                    }
//
//                });
//    }


    @Override
    protected void init() {
        setTitleText("注册");
        mLoginPresenter = new LoginPresenterImpl((EApplication) getApplication(), this);

    }

    @Override
    protected void loadData() {
        phoneNumber = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_STR);
        verity_code = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_SMS);

    }

    /**
     * 错误提示动画
     *
     * @param view
     */
    private void errTips(final View view, String tips) {
        err_tips_tv.setText(tips);
        err_tips_tv.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessageDelayed(TIPS_GONE, 3000);
    }

    @Override
    public boolean isValidUserName(String userName) {
        Pattern pattern = Pattern.compile(
                "^[A-Za-z]{3,20}$|^[\u4e00-\u9fa5]{2,5}$|^[1-9][0-9]{4,15}$");
        boolean rs = pattern.matcher(userName.trim()).find();
        return rs;
    }

    @Override
    public boolean setUerNameError(String error) {
        if (!TextUtils.isEmpty(error)) {
            showToastError(error);
        }
        return true;
    }

    @Override
    public boolean setPasswordError(String error) {
        if (!TextUtils.isEmpty(error)) {
            showToastError(error);
        }
        return true;
    }

    @Override
    public void showLoginProgress(boolean show) {
        if (show) {
            showCricleProgress(null);
        } else {
            hideCricleProgress();
        }
    }

    @Override
    public void showLoginErrorMsg(String msg) {
        hideCricleProgress();
        DialogUtil.showFailedToastByErrorType(RegisterActivity.this, msg);
    }

    @Override
    public void navigateToHome(boolean isBindPhone, String passWord) {
        EJumpManager.jumpToMain(0, RegisterActivity.this);
        this.finish();
    }
}
